package com.yicong.ants.ui.circle.journal;

import android.view.View;

import androidx.databinding.DataBindingUtil;

import com.amap.api.services.core.PoiItem;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.cchao.simplelib.core.JsonHelper;
import com.cchao.simplelib.core.RxBus;
import com.cchao.simplelib.ui.activity.BaseTitleBarActivity;
import com.yicong.ants.Constants;
import com.yicong.ants.R;
import com.yicong.ants.databinding.ItemJournalLocationBinding;
import com.yicong.ants.databinding.JournalLocationActivityBinding;
import com.yicong.ants.utils.AmapHelper;

import java.util.List;

/**
 * @author cch
 * @version 2020/8/22
 */
public class PoiSelectActivity extends BaseTitleBarActivity<JournalLocationActivityBinding> implements View.OnClickListener {

    @Override
    protected int getLayout() {
        return R.layout.journal_location_activity;
    }

    @Override
    protected void initEventAndData() {
        setTitleText("位置选择");
        mDataBind.setClick(this);
        initViews();
    }

    @Override
    protected void onLoadData() {

    }

    private void initViews() {
        switchView(LOADING);
        AmapHelper.doSearchQuery(new PoiSearch.OnPoiSearchListener() {
            @Override
            public void onPoiSearched(PoiResult poiResult, int rCode) {
                if (rCode != 1000) {
                    showToast("附近位置搜索出错 " + rCode);
                    return;
                }
                if (poiResult == null || poiResult.getQuery() == null) {
                    showToast("附近位置没有数据");
                    return;
                }
                // 取得第一页的poiitem数据，页数从数字0开始
                List<PoiItem> poiItems = poiResult.getPois();
                // 当搜索不到poiitem数据时，会返回含有搜索关键字的城市信息
                updateList(poiItems);
                switchView(CONTENT);
            }

            @Override
            public void onPoiItemSearched(PoiItem poiItem, int i) {

            }
        });
    }

    void updateList(List<PoiItem> list) {
        for (PoiItem poiItem : list) {
            ItemJournalLocationBinding binding = DataBindingUtil.inflate(mLayoutInflater
                , R.layout.item_journal_location, mDataBind.linear, false);
            binding.setBean(poiItem);
            binding.setClick(v -> {
                //
                RxBus.get().postEvent(Constants.Event.Circle_Journal_Poi, JsonHelper.toJson(binding.getBean()));
                finish();
            });
            mDataBind.linear.addView(binding.getRoot(), 1);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.clear_location:
                RxBus.get().postEvent(Constants.Event.Circle_Journal_Poi, null);
                finish();
                break;
        }
    }
}
